import os
import subprocess


def combine_bits(input_dir, output_path):

    # 打开128个输入文件
    files = [open(os.path.join(input_dir, f"{i + 1}.bin"), 'rb') for i in range(128)]

    # 读取所有文件的数据到位队列
    bit_streams = []

    for f in files:
        bit_streams.append(f.read())
    tot = len(bit_streams[0]) # 每个文件有多少个字节
    print("Tot bytes:", tot)
    # 按位组合回原始块
    with open(output_path, 'wb') as fout:
        for count in range(tot): # 第count个字节
            for k in range(8):  # 每个字节处理8次
                for i in range(16): # 16个字节
                    byte = 0
                    for j in range(8):
                        # 8个bit
                        byte <<= 1
                        byte |= (bit_streams[i*8+j][count] >> (7 - k)) & 0x01
                    fout.write(bytes([byte])) # 写入字节
    fout.close()
    # 关闭所有文件
    for f in files:
        f.close()


def work():
    base_dir = os.path.dirname(os.path.abspath(__file__)).replace('\\', '/') + "/../../"
    input_dir = base_dir + "/data/client/t0"
    output_path = base_dir + "/data/server/out.bin"
    exec_path = base_dir + "/bin/combine_128.exe"
    # combine_bits(input_dir, output_path)
    subprocess.run([exec_path, input_dir, output_path])
    print("Done!")

if __name__ == '__main__':
    work()